<template>
  <div>
    <Nav>
      <el-breadcrumb-item
        slot="nav"
        v-for="(item,index) in breadcrumbList"
        :key="index"
        :to="{ path : item.href}"
      >{{item.name}}</el-breadcrumb-item>
    </Nav>
    <el-card>
      <!-- 搜索和按钮 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="gerUserList"
            @input="gerUserList"
          >
            <el-button slot="append" icon="el-icon-search" @click="gerUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格数据 -->
      <el-table :data="userList" style="width: 100%" stripe border>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeSwitchActive(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUser(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <!-- 角色分配按钮 -->
            <el-tooltip effect="dark" content="角色分配" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <!-- <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 4, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>-->
      <Pagination
        :handleSizeChange="handleSizeChange"
        :handleCurrentChange="handleCurrentChange"
        :querInfo="queryInfo"
        :total="total"
      ></Pagination>
    </el-card>
      <!-- 点击添加对话框 弹框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="closeDialog">
      <!-- 添加表单 -->
      <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @click="closeEditUser">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 点击分配角色对话框 -->
    <el-dialog title="角色分配" :visible.sync="setDialogVisible" width="50%" @close="closeRoles">
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <p>
          分配新的角色：
          <el-select v-model="setNewRoles" placeholder="请选择">
            <el-option
              v-for="item in getRoles"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="ediltRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Nav from './nav'
import Pagination from './pagination'
export default {
  data() {
    var checkEmail = (rule, value, cb) => {
      // 匹配的次数：？ 0或1次     + 1次或多次   * 随便多少次
      // + 表示匹配前面的内容1次或多次。也就是说，前面的表达式，至少需要出现一次
      // ([a-zA-Z0_-])+   表示的意思就是，a-z\A-Z\0\_\-   这么几个字符区间，必须至少有一个字符生成
      // . * ? + ^ $ 是几个常见的特殊字符
      // . 表示匹配任意字符，除了换行
      // \ 是换行符。就是把一些有特殊含义的字符，将他的特殊含义去掉，把他变成一个纯粹的字符。。比如： ？表示匹配0或1次，则\? 就表示单纯的字符？
      const regEmail = /^([a-zA-Z0_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机
    var checkMobile = (rule, value, cb) => {
      //^  表示开头
      // (0|86|17951)?  表示三个中的一个出现0或1次
      // 13[0-9]   匹配13* 开头的号码
      // 15[0123456789] 匹配 15*开头的号码      [0-9] == [0123456789]
      // 17[678]|18[0-9]|14[57]   这三个，和上面一样
      // (13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])   则这么一整个，表示的是手机号的前3位
      // [0-9]{8}   表示的是0-9的任意一个数字，而且出现8次

      // 整个的含义：区号+三位开头数字+8位普通数字 = 手机号
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      breadcrumbList: [
        {
          name: '首页',
          href: '/welcome',
        },
        {
          name: '用户管理',
        },
        {
          name: '用户列表',
        },
      ],
      userList: [],
      total: 0,
      // 获取用户列表的参数对象
      queryInfo: {
        // 搜索关键字
        query: '',
        // 当前页码
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2,
      },
      dialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      // 验证规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            validator: checkMobile,
            trigger: 'blur',
          },
        ],
      },
      // 修改用户对话框显示与隐藏
      editDialogVisible: false,
      // 修改用户信息
      editForm: {
        // username: '',
        // email: '',
        // mobile: '',
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            validator: checkMobile,
            trigger: 'blur',
          },
        ],
      },
      // 点击分配角色
      setDialogVisible: false,
      // 角色分配一行的信息
      userInfo: {},
      getRoles: [],
      setNewRoles: '',
    }
  },
  methods: {
    async gerUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 显示多少条一页
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.gerUserList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.gerUserList()
    },
    // 监听改变状态
    async changeSwitchActive(switchInfo) {
      const { data: res } = await this.$http.put(
        `users/${switchInfo.id}/state/${switchInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        switchInfo.mg_state = !switchInfo.mg_state
        return this.$message.error('修改用户状态失败')
      }
      this.$message.success('修改用户状态成功')
    },
    // 监听添加用户表单关闭事件
    closeDialog() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定添加用户列表
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        // 如果valid是false就直接返回，不发起请求
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        this.dialogVisible = false
        this.gerUserList()
      })
    },
    // 修改用户对话框
    async editUser(id) {
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200)
        return this.$message.error('查询用户信息失败')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 点击关闭重置用户对话框
    closeEditUser() {
      this.$refs.editFormRef.resetFields()
    },
    // 提交用户修改信息
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          { email: this.editForm.email, mobile: this.editForm.mobile }
        )
        if (res.meta.status !== 200)
          return this.$message.error('修改用户数据失败')
        this.$message.success('修改用户信息成功')
        this.editForm = res.data
        this.editDialogVisible = false
        this.gerUserList()
      })
    },
    // 删除用户信息
    async deleteUser(id) {
      const resconfirmRes = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // 如果用户确认删除，则返回字符串confirm
      // 如果用户点击取消。则返回字符串 cancel
      if (resconfirmRes !== 'confirm') return this.$message.info('已经取消删除')
      // 点击确认删除
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200)
        return this.$message.error('删除用户信息失败')
      this.$message.success('删除用户信息成功')
      this.gerUserList()
    },
    // 点击分配角色
    async setRoles(userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200)
        return this.$message.error('获取分配列表失败')
      this.getRoles = res.data
      this.setDialogVisible = true
    },
    // 点击确定修改角色
    async ediltRoles() {
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.setNewRoles,
        }
      )
      console.log(this.setNewRoles)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.gerUserList()
      this.setDialogVisible = false
    },

    // 关闭角色分配
    closeRoles() {
      ;(this.setNewRoles = ''), (this.userInfo = '')
    },
  },
  created() {
    this.gerUserList()
  },

  components: {
    Nav,
    Pagination
  },
}
</script>
<style lang="less" scoped>
</style>